import React, { useEffect, useState, useCallback, useRef, FC } from "react";
import i18n from "i18n-js";
import moment, { Moment } from "moment";
import { DynamicColors, GStyleSheet, GDynamicValue } from "@/utils/DarkMode";
import { View, Text } from "@tarojs/components";
import homesModel from "@/models/homes";
import deviceListModal, { deviceDefaultName } from "@/models/deviceList";
import languageModal from "@/models/language";
import configWifiModel from '../models/configWifi';
import { goToSuccess, goToFail, postSoftApConfigRes } from '../models/configTool';
import Searching from '../components/Searching';

const softAPIcon = 'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/375869/media/softApIcon_1653300043271.png';
// import { IBaseConfigNetworkProps } from '../models/base/baseConfigNetwork';

const dstyles = GStyleSheet.create({
  container: {
    width: "100%",
    flex: 1,
  },
});

const maxProgress = 100; // 最大进度是100
const congfigTime = 100; // 配网时间100s

const SoftApConfig: FC = React.memo(() => {

  const styles = dstyles.useDynamicStyle();
  const [progress, setProgress] = useState(0);
  const progressRef = useRef(progress);

  useEffect(() => {
    progressRef.current = progress;
  }, [progress])

  const timerRef = useRef<any>(null);

  const endTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  const timerAdd = useCallback(() => {
    if (progressRef.current < maxProgress) {
      setProgress(progressRef.current + 1);
    } else {
      endTimer();
    }
  }, [endTimer]);

  const startTimer = useCallback(() => {
    endTimer();
    timerRef.current = setInterval(timerAdd, (congfigTime / maxProgress) * 1000);
  }, [endTimer, timerAdd])

  const bindDevices = useCallback(async (devices: IDevice[], startMoment: moment.Moment) => {
    console.log('进去aep绑定');
    const device = devices[0];
    const deviceName = deviceDefaultName(device, languageModal);
    const aepRes = await homesModel.addDevice({ device: { ...device, name: deviceName } });
    console.log('aep绑定结果', aepRes);
    if (aepRes.success) {
      const aepDevice = { ...device, ...aepRes.data };
      configWifiModel.addDevice(aepDevice);
      deviceListModal.getDeviceList();
      postSoftApConfigRes({
        productKey: device.productKey,
        success: true,
        res: {},
        startMoment,
      })
      goToSuccess();
    } else {
      postSoftApConfigRes({
        productKey: device.productKey,
        success: false,
        res: aepRes,
        startMoment,
      })
      goToFail();
    }
  }, [])

  const startConfig = useCallback(() => {
    const startMoment = moment();
    configWifiModel.configModel!.startConfig({
      wifiName: configWifiModel.wifiName!,
      password: configWifiModel.password,
      timeout: congfigTime,
    }).then((result) => {
      console.log('配网结果', result);
      if (result.success) {
        const { data } = result;
        console.log('SDK配置成功', data);
        if (data && data.length > 0) {
          configWifiModel.addDevice(data[0]);
          goToSuccess();
          // bindDevices(data, startMoment);
        } else {
          postSoftApConfigRes({
            productKey: configWifiModel.productConfig!.productKey,
            success: false,
            res: result,
            startMoment,
          })
          goToFail();
        }
      } else {
        postSoftApConfigRes({
          productKey: configWifiModel.productConfig!.productKey,
          success: false,
          res: result,
          startMoment
        })
        goToFail();
      }
    });
    startTimer();
  }, [startTimer, bindDevices]);

  const endConfig = useCallback(() => {
    console.log('endConfig');
    configWifiModel.configModel?.endConfig();
    endTimer();
  }, [endTimer]);

  useEffect(() => {
    startConfig();
    return () => {
      endConfig();
    }
  }, []);

  return (
    <View style={styles.container}>
      <Searching progress={progress} icon={softAPIcon} />
    </View>
  );
});

export default SoftApConfig;
